/**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 */
define(['N/search', 'N/record', 'N/runtime', '../common/moment', '../common/txUtil'], function (search, record, runtime, moment, txUtil) {
        function getInputData() {
            var mySearch = initSearch();
            var alls = [];
            var results = mySearch.run().getRange(0, 1000);
            var j = 1;
            while (results.length > 0 && j < 2) {
                for (var i = 0; i < results.length; i++) {
                    var result = results[i];
                    var tmp = {};
                    tmp.id = result.id;
                    alls[alls.length] = tmp;
                }
                results = mySearch.run().getRange(j * 1000, 1000 + j * 1000);
                j++;
            }
            log.debug('alls', JSON.stringify(alls));
            return alls;
        }

        function map(context) {
            var txId = JSON.parse(context.value).id;
            var tx = {};
            tx = getTxRecord(txId);
            log.debug('tx.type:' + tx.type, JSON.stringify(tx));
            try {
                var journalId = createJournal(tx);
                log.audit('create journal success!', journalId);
                record.submitFields({
                    type: 'customrecord_fba_transaction_report',
                    id: tx.id,
                    values: {
                        custrecord_tran_journal_flag: true,
                        custrecord_tran_journal: journalId
                    }
                })

            } catch (e) {
                record.submitFields({
                    type: 'customrecord_fba_transaction_report',
                    id: tx.id,
                    values: {
                        custrecord_tran_journal_flag: true,
                        custrecord_tran_journal_message: JSON.stringify(e)
                    }
                });
                log.error('error', JSON.stringify(e));
            }
        }

        function reduce(context) {
        }

        function summarize(summary) {
        }

        function createJournal(tx) {
            var journal = record.create({type: 'journalentry', isDynamic: true});
            journal.setValue('customform', 135);
            var results = search.create({
                type: 'salesorder',
                columns: ['subsidiary', 'currency'],
                filters: [['custbody_platform_order_id', 'is', tx.orderId]]
            }).run().getRange(0, 1);
            if (results.length > 0) {
                journal.setValue('subsidiary', results[0].getValue('subsidiary'));
                journal.setValue('currency', results[0].getValue('currency'));
            } else {
                //throw "orderId:"+tx.orderId+"不存在";
                journal.setValue('subsidiary', 1);
                journal.setText('currency', tx.currency);
            }

            journal.setValue('custbody_amzn_ord_id', tx.orderId);
            journal.setValue('custbody_amzn_tx_typ', tx.type);
            journal.setValue('custbody_amzn_stl_id', tx.settlementId);
            journal.setValue('custbody_amzn_tx_desc', tx.description);
            journal.setValue('custbody_amzn_tx', tx.id);

            search.create({
                type: 'customrecord_fba_transaction_report',
                columns: [],
                filters: [['custrecord_tran_settlement_id', 'is', tx.settlementId],
                    'and', ['custrecord_tran_type', 'is', tx.type],
                    'and', ['custrecord_tran_order_id', 'is', tx.orderId]]
            }).run().each(function (result) {
                var tx = getTxRecord(result.id);
                if (tx.type === "Adjustment" || tx.type === "Anpassung" || tx.type === "Ajustement" || tx.type === "Ajuste" || tx.type === "Modifica" || tx.type === "調整") {
                    search.create({
                        type: 'customrecord_tx_journal_setting',
                        columns: ['custrecord_setting_field', 'custrecord_setting_debit', 'custrecord_setting_credit'],
                        filters: [['custrecord_setting_country', 'is', tx.country],
                            'and', ['custrecord_setting_type', 'is', tx.type],
                            'and', ['custrecord_setting_description', 'is', tx.description]]
                    }).run().each(function (result) {
                        var text = result.getText('custrecord_setting_field');
                        var str = titleCase(text);
                        var debitAccount = result.getValue('custrecord_setting_debit');
                        var creditAccount = result.getValue('custrecord_setting_credit');
                        var amount = eval("tx." + str);
                        if (amount !== null && amount !== undefined && amount !== '' && amount !== 0) {
                            addNewItemLine(journal, amount, tx, debitAccount, creditAccount);
                        }
                        return true;
                    });
                } else {
                    search.create({
                        type: 'customrecord_tx_journal_setting',
                        columns: ['custrecord_setting_field', 'custrecord_setting_debit', 'custrecord_setting_credit'],
                        filters: [['custrecord_setting_country', 'is', tx.country],
                            'and', ['custrecord_setting_type', 'is', tx.type]]
                    }).run().each(function (result) {
                        var text = result.getText('custrecord_setting_field');
                        var str = titleCase(text);
                        var debitAccount = result.getValue('custrecord_setting_debit');
                        var creditAccount = result.getValue('custrecord_setting_credit');
                        var amount = eval("tx." + str);
                        if (amount !== null && amount !== undefined && amount !== '' && Number(amount !== 0)) {
                            addNewItemLine(journal, amount, tx, debitAccount, creditAccount);
                        }
                        return true;
                    });
                }

            });


            if (journal.getLineCount('line') === 0) {
                throw "创建日记账的金额为0,不需要创建!";
            }

            var journalId = journal.save();
            return journalId;

            /*   if (tx.currency === "USD") {//美国
                   if (tx.type === 'order') {
                       //shippingCredits 运费  借:1122.02 应收账款 id:122,贷:6601.24销售费用:其他费用 id:970;
                       addNewItemLine(journal, tx.shippingCredits, tx, 122, 970);
                       //sellingFees 亚马逊平台费  借:6601.20销售费用:平台交易费id:966 	贷:1122.02应收账款 id:122
                       addNewItemLine(journal, tx.sellingFees, tx, 966, 122);
                       //otherTxFees 其他交易费 借:6601.24销售费用:其他费用 id:970	贷:1122应收账款 id:122
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       //other  其他  借:6601.24销售费用:其他费用 id:970	贷:1122应收账款 id:122
                       addNewItemLine(journal, tx.other, tx, 970, 122);
                   } else if (tx.type === 'Refund') {
                       //shippingCredits 运费  借:6601.24销售费用:其他费用 id:970,	贷:1122应收账款 id:122
                       addNewItemLine(journal, tx.shippingCredits, tx, 970, 122);
                       //sellingFees 亚马逊平台费  借:1122应收账款 id:122	贷:6601.20销售费用 : 平台交易费 id:966
                       addNewItemLine(journal, tx.sellingFees, tx, 122, 966);
                       //otherTxFees 其他交易费 借:6601.24销售费用:其他费用 id:970	贷:1122应收账款 id:122
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       //other  其他  借:6001.02主营业务收入 id:910	贷:1122应收账款 id:122
                       addNewItemLine(journal, tx.other, tx, 910, 122);
                   } else if (tx.type === 'FBA Inventory Fee') {
                       //other  其他  借:6601.19销售费用 : FBA费（仓储管理费）id:965	贷:1122应收账款 id:122
                       addNewItemLine(journal, tx.other, tx, 965, 122);
                   } else if (tx.type === 'Lightning Deal Fee') {
                       //otherTxFees 其他交易费 借:6601.17.01.03销售费用 : 促销费 : 站内推广 :LD Fee id:951	贷:1122应收账款 id:122
                       addNewItemLine(journal, tx.otherTxFees, tx, 951, 122);
                   } else if (tx.type === 'Service Fee') {
                       //sellingFees 亚马逊平台费  借:6601.17.01.02销售费用 : 促销费 : 站内推广 : Pr/cp id:950	贷:1122应收账款 id:122
                       addNewItemLine(journal, tx.sellingFees, tx, 950, 122);
                       //otherTxFees 其他交易费 借:6601.17.01.01销售费用 : 促销费 : 站内推广 : SP id:949	贷:1122应收账款 id:122
                       addNewItemLine(journal, tx.otherTxFees, tx, 949, 122);
                       //other  其他  借:6601.24销售费用 : 其他费用 id:970	贷:1122应收账款 id:122
                       addNewItemLine(journal, tx.other, tx, 970, 122);
                   } else if (tx.type === 'Transfer') {
                       //other  其他  借:1012其他货币资金 id:	贷:1122应收账款 id:122
                       addNewItemLine(journal, tx.other, tx, 1907, 122);
                   } else if (tx.type === 'Adjustment') {

                   }
               }

               if (tx.currency === "CAD") {
                   if (tx.type === 'Order') {
                       addNewItemLine(journal, tx.shippingCredits, tx, 122, 970);
                       addNewItemLine(journal, tx.sellingFees, tx, 966, 122);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 970, 122);
                   } else if (tx.type === 'Refund') {
                       addNewItemLine(journal, tx.shippingCredits, tx, 970, 122);
                       addNewItemLine(journal, tx.sellingFees, tx, 122, 966);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 910, 122);
                   } else if (tx.type === 'FBA Inventory Fee') {
                       addNewItemLine(journal, tx.other, tx, 965, 122);
                   } else if (tx.type === 'Lightning Deal Fee') {
                       addNewItemLine(journal, tx.otherTxFees, tx, 951, 122);
                   } else if (tx.type === 'Service Fee') {
                       addNewItemLine(journal, tx.otherTxFees, tx, 949, 122);
                       addNewItemLine(journal, tx.other, tx, 970, 122);
                   } else if (tx.type === 'Transfer') {
                       addNewItemLine(journal, tx.other, tx, 1907, 122);
                   }
               }

               if (tx.currency === "EUR") {
                   if (tx.type === "Bestellung") {
                       addNewItemLine(journal, tx.shippingCredits, tx, 122, 970);
                       addNewItemLine(journal, tx.sellingFees, tx, 966, 122);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 970, 122);
                   } else if (tx.type === "Erstattung") {
                       addNewItemLine(journal, tx.shippingCredits, tx, 970, 122);
                       addNewItemLine(journal, tx.sellingFees, tx, 122, 966);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 910, 122);
                   } else if (tx.type === "Bestellung_Wiedereinzug") {
                       addNewItemLine(journal, tx.total, tx, 122, 988);
                   } else if (tx.type === "Erstattung_Wiedereinzug") {
                       addNewItemLine(journal, tx.total, tx, 988, 122);
                   } else if (tx.type === "Blitzangebotsgebühr") {
                       addNewItemLine(journal, tx.otherTxFees, tx, 951, 122);
                   } else if (tx.type === "Erstattung durch Rückbuchung") {
                       // // 销售（行字段）	                 Umsätze	6001主营业务收入	1122应收账款
                       // // 亚马逊平台费（行字段）	Verkaufsgebühren	1122应收账款	6601.20销售费用 : 平台交易费
                       addNewItemLine(journal, tx.productSales, tx, 910, 122);
                       addNewItemLine(journal, tx.sellingFees, tx, 122, 966);
                   } else if (tx.type === "Übertrag") {
                       addNewItemLine(journal, tx.other, tx, 1907, 122)
                   } else if (tx.type === "Servicegebühr") {
                       addNewItemLine(journal, tx.otherTxFees, tx, 949, 122);
                   } else if (tx.type === "Versand durch Amazon Lagergebühr") {
                       addNewItemLine(journal, tx.other, tx, 965, 122);
                   }
               }

               if (tx.currency === "GBP") {
                   if (tx.type === 'Order') {
                       addNewItemLine(journal, tx.shippingCredits, tx, 122, 970);
                       addNewItemLine(journal, tx.sellingFees, tx, 966, 122);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 970, 122);
                   } else if (tx.type === 'Refund') {
                       addNewItemLine(journal, tx.shippingCredits, tx, 970, 122);
                       addNewItemLine(journal, tx.sellingFees, tx, 122, 966);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 910, 122);
                   } else if (tx.type === 'FBA Inventory Fee') {
                       addNewItemLine(journal, tx.other, tx, 965, 122);
                   } else if (tx.type === 'Lightning Deal Fee') {
                       addNewItemLine(journal, tx.otherTxFees, tx, 951, 122);
                   } else if (tx.type === "Order_Retrocharge") {
                       addNewItemLine(journal, tx.total, tx, 122, 988);
                   } else if (tx.type === "Refund_Retrocharge") {
                       addNewItemLine(journal, tx.total, tx, 988, 122);
                   } else if (tx.type === 'Service Fee') {
                       addNewItemLine(journal, tx.otherTxFees, tx, 949, 122);
                   } else if (tx.type === 'Transfer') {
                       addNewItemLine(journal, tx.other, tx, 1907, 122);
                   }
               }

               if (tx.currency === "EUR") {
                   if (tx.type === 'Commande') {
                       addNewItemLine(journal, tx.shippingCredits, tx, 122, 970);
                       addNewItemLine(journal, tx.sellingFees, tx, 966, 122);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 970, 122);
                   } else if (tx.type === 'Remboursement') {
                       addNewItemLine(journal, tx.shippingCredits, tx, 970, 122);
                       addNewItemLine(journal, tx.sellingFees, tx, 122, 966);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 910, 122);
                   } else if (tx.type === 'Frais de service') {
                       addNewItemLine(journal, tx.other, tx, 950, 122);
                   } else if (tx.type === 'Frais de stock Expédié par Amazon') {
                       addNewItemLine(journal, tx.other, tx, 965, 122);
                   } else if (tx.type === "Order_Retrocharge") {
                       addNewItemLine(journal, tx.total, tx, 122, 988);
                   } else if (tx.type === "Refund_Retrocharge") {
                       addNewItemLine(journal, tx.total, tx, 988, 122);
                   } else if (tx.type === "Tarif de la Vente Flash") {
                       addNewItemLine(journal, tx.total, tx, 951, 122);
                   } else if (tx.type === 'Transfert') {
                       addNewItemLine(journal, tx.other, tx, 1907, 122);
                   }
               }

               if (tx.currency === "EUR") {
                   if (tx.type === 'Pedido') {
                       addNewItemLine(journal, tx.shippingCredits, tx, 122, 970);
                       addNewItemLine(journal, tx.sellingFees, tx, 966, 122);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 970, 122);
                   } else if (tx.type === 'Reembolso') {
                       addNewItemLine(journal, tx.shippingCredits, tx, 970, 122);
                       addNewItemLine(journal, tx.sellingFees, tx, 122, 966);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 910, 122);
                   } else if (tx.type === "Cargo retroactivo") {
                       addNewItemLine(journal, tx.total, tx, 122, 988);
                   } else if (tx.type === "Refund_Retrocharge") {
                       addNewItemLine(journal, tx.total, tx, 988, 122);
                   } else if (tx.type === 'Tarifas de inventario de Logística de Amazon') {
                       addNewItemLine(journal, tx.other, tx, 965, 122);
                   } else if (tx.type === 'Tarifa de Oferta flash') {
                       addNewItemLine(journal, tx.otherTxFees, tx, 951, 122);
                   } else if (tx.type === 'Tarifa de prestación de servicio') {
                       addNewItemLine(journal, tx.otherTxFees, tx, 949, 122);
                   } else if (tx.type === 'Transferir') {
                       addNewItemLine(journal, tx.other, tx, 1907, 122);
                   }
               }

               if (tx.currency === "EUR") {
                   if (tx.type === 'Ordine') {
                       addNewItemLine(journal, tx.shippingCredits, tx, 122, 970);
                       addNewItemLine(journal, tx.sellingFees, tx, 966, 122);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 970, 122);

                   } else if (tx.type === 'Rimborso') {
                       addNewItemLine(journal, tx.shippingCredits, tx, 970, 122);
                       addNewItemLine(journal, tx.sellingFees, tx, 122, 966);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 910, 122);
                   } else if (tx.type === 'Costo di stoccaggio Logistica di Amazon') {
                       addNewItemLine(journal, tx.other, tx, 965, 122);
                   } else if (tx.type === 'Tariffa dell’Offerta Lampo') {
                       addNewItemLine(journal, tx.otherTxFees, tx, 951, 122);
                   } else if (tx.type === 'Commissione di servizio') {
                       addNewItemLine(journal, tx.otherTxFees, tx, 949, 122);
                   } else if (tx.type === "Order_Retrocharge") {
                       addNewItemLine(journal, tx.total, tx, 122, 988);
                   } else if (tx.type === "Refund_Retrocharge") {
                       addNewItemLine(journal, tx.total, tx, 988, 122);
                   } else if (tx.type === 'Trasferimento') {
                       addNewItemLine(journal, tx.other, tx, 1907, 122);
                   }
               }

               if (tx.currency === "JPY") {
                   if (tx.type === '注文') {
                       addNewItemLine(journal, tx.shippingCredits, tx, 122, 970);
                       addNewItemLine(journal, tx.sellingFees, tx, 966, 122);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 970, 122);
                   } else if (tx.type === '返金') {
                       addNewItemLine(journal, tx.shippingCredits, tx, 970, 122);
                       addNewItemLine(journal, tx.sellingFees, tx, 122, 966);
                       addNewItemLine(journal, tx.otherTxFees, tx, 970, 122);
                       addNewItemLine(journal, tx.other, tx, 910, 122);
                   } else if (tx.type === 'FBA 在庫関連の手数料') {
                       addNewItemLine(journal, tx.other, tx, 965, 122);
                   } else if (tx.type === '数量限定タイムセール手数料') {
                       addNewItemLine(journal, tx.otherTxFees, tx, 951, 122);
                   } else if (tx.type === '注文外料金') {
                       addNewItemLine(journal, tx.otherTxFees, tx, 950, 122);
                       addNewItemLine(journal, tx.other, tx, 964, 122);
                   } else if (tx.type === '振込み') {
                       addNewItemLine(journal, tx.other, tx, 1907, 122);
                   }
               }*/

        }


        function addNewItemLine(rec, amount, tx, debitAccount, creditAccount) {
            var total = Math.abs(txUtil.getFormattedAmount(amount, tx.marketplace));
            rec.selectNewLine('line');
            rec.setCurrentSublistValue('line', 'account', debitAccount);
            rec.setCurrentSublistValue('line', 'debit', total);
            rec.setCurrentSublistText('line', 'custcol_amzn_sku', tx.sku);
            rec.setCurrentSublistValue('line', 'custcol_journal_country', '');
            rec.setCurrentSublistValue('line', 'custcol_platform', 'Amazon');
            rec.setCurrentSublistValue('line', 'custcol_pf_sub_dept', '');
            rec.setCurrentSublistValue('line', 'custcol_journal_quantity', tx.quantity);
            rec.setCurrentSublistValue('line', 'custcol_journal_shpping_credits', tx.shippingCredits);
            rec.setCurrentSublistValue('line', 'custcol_sales_tax_collected', tx.salesTaxCollected);
            rec.setCurrentSublistValue('line', 'custcol_marketplace_facilitator_tax', tx.marketplaceTax);
            rec.setCurrentSublistValue('line', 'custcol_amzn_selling_fee', tx.sellingFees);
            rec.setCurrentSublistValue('line', 'custcol_other_tx_fee', tx.otherTxFees);
            rec.setCurrentSublistValue('line', 'custcol_amzn_other', tx.other);
            rec.setCurrentSublistValue('line', 'custcol_amzn_total', tx.total);
            rec.commitLine('line');

            rec.selectNewLine('line');
            rec.setCurrentSublistValue('line', 'account', creditAccount);
            rec.setCurrentSublistValue('line', 'credit', total);
            rec.setCurrentSublistText('line', 'custcol_amzn_sku', tx.sku);
            rec.setCurrentSublistValue('line', 'custcol_journal_country', '');
            rec.setCurrentSublistValue('line', 'custcol_platform', 'Amazon');
            rec.setCurrentSublistValue('line', 'custcol_pf_sub_dept', '');
            rec.setCurrentSublistValue('line', 'custcol_journal_quantity', tx.quantity);
            rec.setCurrentSublistValue('line', 'custcol_journal_shpping_credits', tx.shippingCredits);
            rec.setCurrentSublistValue('line', 'custcol_sales_tax_collected', tx.salesTaxCollected);
            rec.setCurrentSublistValue('line', 'custcol_marketplace_facilitator_tax', tx.marketplaceTax);
            rec.setCurrentSublistValue('line', 'custcol_amzn_selling_fee', tx.sellingFees);
            rec.setCurrentSublistValue('line', 'custcol_other_tx_fee', tx.otherTxFees);
            rec.setCurrentSublistValue('line', 'custcol_amzn_other', tx.other);
            rec.setCurrentSublistValue('line', 'custcol_amzn_total', tx.total);
            rec.commitLine('line');

        }

        function getTxRecord(txId) {
            var txRecord = record.load({type: 'customrecord_fba_transaction_report', id: txId, isDynamic: true});
            var tx = {};
            tx.id = txId;
            tx.sku = txRecord.getValue('custrecord_tran_sku');
            tx.orderId = txRecord.getValue('custrecord_tran_order_id');
            tx.quantity = txRecord.getValue('custrecord_tran_quantity');
            tx.marketplace = txRecord.getValue('custrecord_tran_marketplace');
            tx.productSales = txRecord.getValue('custrecord_tran_product_sales');
            tx.shippingCredits = txRecord.getValue('custrecord_tran_shipping_credits');
            tx.giftWrapCredits = txRecord.getValue('custrecord_tran_gift_wrap_credits');
            tx.promotionalRebates = txRecord.getValue('custrecord_tran_promotional_rebates');
            tx.salesTaxCollected = txRecord.getValue('custrecord_tran_sales_tax_collected');
            tx.marketplaceTax = txRecord.getValue('custrecord_tran_marketplace_facilitator');
            tx.sellingFees = txRecord.getValue('custrecord_tran_selling_fees');
            tx.fbaFees = txRecord.getValue('custrecord_tran_fba_fees');
            tx.otherTxFees = txRecord.getValue('custrecord_tran_other_transaction_fees');
            tx.other = txRecord.getValue('custrecord_tran_other');
            tx.total = txRecord.getValue('custrecord_tran_total');
            tx.datetime = txRecord.getValue('custrecord_tran_datetime');
            tx.settlementId = txRecord.getValue('custrecord_tran_settlement_id');
            tx.description = txRecord.getValue('custrecord_tran_description');
            tx.type = txRecord.getValue('custrecord_tran_type');
            tx.storeId = txRecord.getValue('custrecord_tran_store_information');

            tx.country = txRecord.getValue('custrecord_tran_country');
            tx.currency = txRecord.getText('custrecord_tran_currency');

            return tx;
        }

        function initSearch() {
            var mySearch = search.create({
                type: 'customrecord_fba_transaction_report',
                filters: [['custrecord_tran_journal_flag', 'is', 'F'], 'and', ['custrecord_tran_journal', 'isempty', '']]
            });
            return mySearch;
        }

        function titleCase(str) {

            //str=str.toLowerCase();
            var array = str.toLowerCase().split(" ");
            for (var i = 1; i < array.length; i++) {
                array[i] = array[i].replace(array[i][0], array[i][0].toUpperCase());
            }
            array = array.join(" ");
            array = array.replace(/\s/g, "");
            return array;
        }

        return {
            getInputData: getInputData,
            map: map,
            reduce: reduce,
            summarize: summarize
        };
    }
);